﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace NFinal.Compile.Template
{
    class Razor
    {
        public void GetWriteCode(StringBuilder sb, IEnumerable<System.Web.Razor.Parser.SyntaxTree.SyntaxTreeNode> trees)
        {
            System.Web.Razor.Parser.SyntaxTree.Block block = null;
            System.Web.Razor.Parser.SyntaxTree.Span span = null;
            foreach (var tr in trees)
            {
                if (tr.IsBlock)
                {
                    block = tr as System.Web.Razor.Parser.SyntaxTree.Block;
                    switch (block.Type)
                    {
                        case System.Web.Razor.Parser.SyntaxTree.BlockType.Expression:
                            GetWriteCode(sb, block.Children); break;
                        case System.Web.Razor.Parser.SyntaxTree.BlockType.Statement:
                            GetWriteCode(sb, block.Children); break;
                    }
                }
                else
                {
                    span = tr as System.Web.Razor.Parser.SyntaxTree.Span;
                    switch (span.Kind)
                    {
                        case System.Web.Razor.Parser.SyntaxTree.SpanKind.Code:
                            if (span.Parent.Type == System.Web.Razor.Parser.SyntaxTree.BlockType.Expression)
                            {
                                sb.AppendLine(string.Format("Write({0});", span.Content));
                            }
                            else
                            {
                                sb.AppendLine(span.Content);
                            }
                            break;
                        case System.Web.Razor.Parser.SyntaxTree.SpanKind.Comment:
                            break;
                        case System.Web.Razor.Parser.SyntaxTree.SpanKind.Markup:
                            sb.AppendLine(string.Format("Write(\"{0}\");", span.Content));
                            break;
                        case System.Web.Razor.Parser.SyntaxTree.SpanKind.MetaCode:
                            break;
                        case System.Web.Razor.Parser.SyntaxTree.SpanKind.Transition:
                            break;
                    }
                }
            }
        }
        public string Render(TextReader tr)
        {
            System.Web.Razor.Parser.RazorParser parser = new System.Web.Razor.Parser.RazorParser(
                new System.Web.Razor.Parser.CSharpCodeParser()
                , new System.Web.Razor.Parser.HtmlMarkupParser());
            parser.DesignTimeMode = false;
            var results = parser.Parse(tr);
            StringBuilder sb = new StringBuilder();
            GetWriteCode(sb, results.Document.Children);
            return sb.ToString();
        }
    }
}
